//
//  OAuthViewController.swift
//  Practice
//
//  Created by miaozhihui on 2016/12/14.
//  Copyright © 2016年 DeKuTree. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD

/// 用户登录控制器
class OAuthViewController: UIViewController {

    private lazy var webView = WKWebView()
    
    // MARK: - 监听方法
    @objc fileprivate func close() {
        // 隐藏加载框
        SVProgressHUD.dismiss()
        // 发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
        // 返回界面
        dismiss(animated: true, completion: nil)
    }
    
    /// 自动填充用户名和密码
    @objc private func autoFill() {
        
        let js = "document.getElementById('userId').value = '15896657240';" + "document.getElementById('passwd').value = '521miao';"
        
        webView.evaluateJavaScript(js, completionHandler: nil)
    }
    
    override func loadView() {
        view = webView
        webView.navigationDelegate = self
        // 取消滚动
        webView.scrollView.isScrollEnabled = false
        // 设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(autoFill))
        navigationController?.navigationBar.tintColor = UIColor.orange
        navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray]
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        // 加载页面
        webView.load(URLRequest(url: NetworkTools.sharedTools.oauthURL))
    }
}

// MARK: - webView代理
extension OAuthViewController:WKNavigationDelegate {
    
    /// 开始临时的导航
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - navigation: 临时的导航
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        SVProgressHUD.show()
        print(webView.url ?? "无效网址")
        print(navigation)
    }
    
    /// 收到服务器重定向
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - navigation: 临时的导航
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        
        // 判断主机是否是 www.baidu.com
        guard let url = webView.url, url.host == "www.baidu.com" else {
            return
        }
        
        // 判断授权码是否存在
        guard let query = url.query,query.hasPrefix("code=") else {
            close()
            return
        }
        
        // 授权码
        let code = query.substring(from: "code=".endIndex)
        
        print("授权码是 " + code)
        
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code: code) { (isSuccessed) in
            SVProgressHUD.dismiss()
            if isSuccessed {
                // 关闭窗口
                self.close()
            } else {
                SVProgressHUD.showError(withStatus: "网络请求失败")
            }
        }
        webView.stopLoading()
    }
    
    /// 完成导航
    ///
    /// - Parameters:
    ///   - webView: webView
    ///   - navigation: 临时的导航
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
        print(navigation)
    }
}
